package org.apache.seatunnel;

import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class utilTest {

    public static void main(String[] args) throws Exception {
        // The company key pair has been generated in advance
        // and stored in pub.txt and pri.txt respectively

        String data = "Hello, World!";
        // Encrypt using public key
        byte[] cipherData = clientEncrypt(data.getBytes(), new File("pub.txt"));

        // Encode encrypted data using Base64
        String encryptedBase64 = Base64.getEncoder().encodeToString(cipherData);

        System.out.println("Encrypted and Base64 encoded Data: " + encryptedBase64);

        // Decode Base64 and decrypt
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedBase64);
        byte[] decryptedBytes = serverDecrypt(decodedBytes, new File("pri.txt"));

        System.out.println("Decrypted Data: " + new String(decryptedBytes));
    }

    private static byte[] clientEncrypt(byte[] plainData, File pubFile) throws Exception {
        // Read the public key file and create a public key object
        PublicKey pubKey = RSAUtils.getPublicKey(IOUtils.readFile(pubFile));
        // Encrypt data with public key
        return RSAUtils.encrypt(plainData, pubKey);
    }

    private static byte[] serverDecrypt(byte[] cipherData, File priFile) throws Exception {
        // Read the private key file and create a private key object
        PrivateKey priKey = RSAUtils.getPrivateKey(IOUtils.readFile(priFile));
        // Decrypt data with private key
        return RSAUtils.decrypt(cipherData, priKey);
    }
}
